package com.ipcamera.demo.h5.presenter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import io.reactivex.disposables.Disposable;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.ipcamera.demo.h5.H5Info;
import com.ipcamera.demo.h5.H5Utils;
import com.ipcamera.demo.h5.contract.H5Contract;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;


/**
 * author: veepai
 * date: 2020/08/12
 * description:
 */
public class H5Presenter implements H5Contract.Presenter {

    private H5Contract.View mView;
    private Context mContent;
    private boolean isClearHistory;
    private H5Info info;

    H5Utils mH5Utils;

    public H5Presenter(H5Contract.View mView) {
        this.mView = mView;
        mContent = mView.getContext();
        mH5Utils = new H5Utils();
    }

    public void initWeb(BridgeWebView webView, H5Info info) {
        this.info = info;
        setWebViewClient(webView);
        //传给JS的数据

        registerDefNativeCallHandler(webView, "getUserid", "10605921");

        registerDefNativeCallHandler(webView, "getAuthkey", "");
        registerDefNativeCallHandler(webView, "getLanguage", "ZH");
        registerDefNativeCallHandler(webView, "getOEMID", "OEM");
        registerDefNativeCallHandler(webView, "getFlowPageColor", "");

        registerDefNativeCallHandler(webView, "getIccid", info.ccid);
        registerDefNativeCallHandler(webView, "signalStrength", info.signa);
        registerDefNativeCallHandler(webView, "getOperator", info.operator);

        //JS回调方式
        registerNativeCallHandler(webView, "configNavigationBarOrder");
        registerNativeCallHandler(webView, "configNavigationBarOrderCno");
        registerNativeCallHandler(webView, "configNavigationBarColor");
        registerNativeCallHandler(webView, "configNavigationBarHidden");
        registerNativeCallHandler(webView, "configNavigationBarRightButtons");
        registerNativeCallHandler(webView, "configStatusBarHidden");
        registerNativeCallHandler(webView, "configStatusBarStyle");
        registerNativeCallHandler(webView, "scanPage");
        registerNativeCallHandler(webView, "displayDiscountCoupon");
        registerNativeCallHandler(webView, "newPage");

        registerNativeCallHandler(webView, "payPage");
        registerNativeCallHandler(webView, "pay");
        registerNativeCallHandler(webView, "resumedPage");
        registerNativeCallHandler(webView, "paySuccessPage");
        registerNativeCallHandler(webView, "queryProductInfo");
        registerNativeCallHandler(webView, "getDeviceCover");
        registerNativeCallHandler(webView, "showMessage");
        registerNativeCallHandler(webView, "set_update_push_user.cgi");

        registerNativeCallHandler(webView, "supportCloud"); //是否支持云储存
        registerNativeCallHandler(webView, "supportCry"); //是否支持哭声
        registerNativeCallHandler(webView, "supportLeave"); //是否支持离岗
        registerNativeCallHandler(webView, "getDeviceCover"); //获取设备图片
        setWebChromeClient(webView);
    }

    public void setWebViewClient(final BridgeWebView webView) {
        //什么都不做的Disposable
        final Disposable disposable = getEmptyDisposable();
        //显示加载
        webView.setWebViewClient(new BridgeWebViewClient(webView) {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            protected void onCustomPageFinishd(WebView view, String url) {
                super.onCustomPageFinishd(view, url);


                //清楚历史记录 支付完成跳转到支付成功页面，返回后如果需要回到首页，在首页加载成功后清楚历史记录，以便回退按钮可以直接退出
                if (isClearHistory) {
                    view.clearHistory();
                    isClearHistory = false;
                }
                if (!disposable.isDisposed()) {
                    //关闭加载
                }
                //加载完后再调用一次JS的WindowLoading方法，初始化一些配置
                callWindowLoading(webView);
            }
        });
    }

    public void setWebChromeClient(BridgeWebView webView) {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.d("接受到标题 title = %s", title);
                mView.setTitle(title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

                Log.d("veepai", "url"+url+ "message"+message);
                // TODO: 2019-07-05 HJH 标题拦截

                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

                return super.onJsConfirm(view, url, message, result);
            }

            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                if (newProgress >= 100) {
                    mView.closeDialog();
                }
            }
        });
    }

    public void setClearHistory() {
        isClearHistory = true;
    }

    /**
     * 调用js方法，开始加载相关参数
     */
    public void callWindowLoading(BridgeWebView webView) {
        webView.callHandler("WindowLoading", null, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
    }



    private void registerDefNativeCallHandler(BridgeWebView webView, final String method, final String value) {
        webView.registerHandler(method, new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                if (function != null) {
                    function.onCallBack(value);
                }
            }
        });
    }

    private void registerNativeCallHandler(BridgeWebView webView, final String method) {
        if (mView == null) return;
        webView.registerHandler(method, new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                callHandler(method, data, function);
            }
        });
    }

    private void callHandler(String method, String data, CallBackFunction function) {

        if (TextUtils.equals("configNavigationBarColor", method)) {
            //设置状态栏颜色
            mView.configNavigationBarColor(data);
            function.onCallBack("success");
        } else if (TextUtils.equals("configNavigationBarHidden", method)) {
            mView.configNavigationBarHidden(!TextUtils.equals("0", data));
        } else if (TextUtils.equals("configNavigationBarOrder", method)) {
            mView.configNavigationBarOrder(data);
        } else if (TextUtils.equals("configStatusBarHidden", method)) {
            mView.configStatusBarHidden(!TextUtils.equals("0", data));
        } else if (TextUtils.equals("configNavigationBarOrderCno", method)) {
            mView.configNavigationBarOrderCno(data);
        } else if (TextUtils.equals("configNavigationBarRightButtons", method)) {
            //设置状态栏按钮信息
            mView.configNavigationBarRightButtoninfo(data);
        } else if (TextUtils.equals("configStatusBarStyle", method)) {
            mView.configStatusBarStyle(TextUtils.equals("0", data));
        } else if (TextUtils.equals("scanPage", method)) {
            //跳转扫码页面
            processScanPage(data, function);
        } else if (TextUtils.equals("displayDiscountCoupon", method)) {
            processDisplayDiscountCoupon(data);
        } else if (TextUtils.equals("newPage", method)) {
            //跳转新页面
            mView.newPage(data);
            function.onCallBack("success");
        } else if (TextUtils.equals("payPage", method)) {
            //跳转支付页面
           // mView.payPage(mH5Utils.processPayPageCall(data, function));
            //function.onCallBack("success");
        } else if (TextUtils.equals("pay", method)) {
            //调用谷歌支付
            //mH5Utils.googleBuy(data, mView, function);
        } else if (TextUtils.equals("paySuccessPage", method)) {
            //支付成功
            processPaySuccessPage(data);
        } else if (TextUtils.equals("queryProductInfo", method)) {
            //查询订单信息
            processQueryProductInfo(data, function);
        } else if (TextUtils.equals("getDeviceCover", method)) {
            //获取设备封面
            getDeviceCover(data, function);
        } else if (TextUtils.equals("showMessage", method)) {
            //显示对话框
            mView.showMessage(data);
            function.onCallBack("success");
        } else if (TextUtils.equals("set_update_push_user.cgi", method)) {
            //发送cgi指令
            mH5Utils.cgi(info, function);
        } else if (TextUtils.equals("supportCloud", method)) {
            //是否支持云存储
            //mH5Utils.isCloud(mContent, data, function);
        } else if (TextUtils.equals("supportCry", method)) {
            //是否支持哭声监测
           // mH5Utils.isTry(mContent, data, function);
        } else if (TextUtils.equals("supportLeave", method)) {
            //是否支持离岗
           // mH5Utils.isAiDepart(mContent, data, function);
        } else  if(TextUtils.equals("resumedPage", method))
        {
            Log.e("veepai","resumedPage" + data);
           // mView.newPage(data);
           // function.onCallBack("success");
        }
    }

    /**
     * 获取设备封面
     */
    private void getDeviceCover(String data, CallBackFunction function) {
        if (function != null) {


        }
        return;
    }

    public void scanCouponResult(String coupon) {
        if (mScanPageFunction != null) {

            mScanPageFunction.onCallBack(coupon);
        }
    }

    private CallBackFunction mScanPageFunction;

    private void processScanPage(String data, CallBackFunction function) {
        this.mScanPageFunction = function;
        mView.scanPage();
    }

    /**
     * 处理显示优惠券页面，解析产品Id
     */
    private void processDisplayDiscountCoupon(String data) {
        String productId = null;
        try {
            JSONObject obj = new JSONObject(data);
            productId = obj.optString("productId");
        } catch (Exception e) {

        }
        mView.displayDiscountCoupon(productId);
    }

    /**
     * 查询产品信息 （JS传⼊：产品ID数组Json串	回传：产品信息数组Json串）
     */
    private void processQueryProductInfo(String data, CallBackFunction function) {
      /*  LogUtils.i("queryProductInfo------------" + data);
        List<String> ids = new ArrayList<>();
        try {
//            JSONArray array = new JSONArray(data);// 旧版的数据解析
            JSONObject json = new JSONObject(data); //2020/6/22 新版本解析
            JSONArray array = json.optJSONArray("array");
            int len = array.length();
            for (int i = 0; i < len; i++) {
                String id = array.optString(i);
                ids.add(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Logger.e("ids = " + ids);

        //查询商品价格
        CommonCallback mCommonCallback = new CommonCallback<List<ProductInfo>>() {
            @Override
            public void call(List<ProductInfo> result) {
                String mCacheProductInfoJson = null;
                if (result == null || result.isEmpty()) {
                    mCacheProductInfoJson = null;
                } else {
                    mCacheProductInfoJson = JSON.toJSONString(result);
                }
                LogUtils.i("查询到的产品信息-" + mCacheProductInfoJson);
                Logger.d("查询到的产品信息toJson：" + mCacheProductInfoJson);
                if (function != null) {
                    function.onCallBack(mCacheProductInfoJson);
                }
            }
        };*/

//        if (SystemUtil.isHW()) { //华为
//            HmsPayManager.getInstance((Activity) mContent).queryProducts(ids, mCommonCallback);
//        } else {
           // mH5Utils.queryProductInfoToGoogle(mContent, ids, mCommonCallback);
//        }
    }

    /**
     * 处理支付成功页面
     */
    private void processPaySuccessPage(String data) {
        String title = null;
        String money = null;
        String orderId = null;
        String type = null;
        try {
            JSONObject json = new JSONObject(data);
            title = json.optString("title");
            money = json.optString("money");
            orderId = json.optString("orderId");
            type = json.optString("type");
        } catch (JSONException e) {

        }
        mView.paySuccessPage(title, money, orderId, type);
    }

    private Disposable getEmptyDisposable() {
        return new Disposable() {
            AtomicBoolean disposed = new AtomicBoolean(false);

            @Override
            public void dispose() {
                disposed.set(true);
            }

            @Override
            public boolean isDisposed() {
                return disposed.get();
            }
        };
    }
}

